package com.hlkj.baojin.controller;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hlkj.baojin.entity.dto.DeviceDto;
import com.hlkj.baojin.entity.dto.MonitorDto;
import com.hlkj.baojin.entity.vo.CameraInfo;
import com.hlkj.baojin.entity.vo.Organization;
import com.hlkj.baojin.service.CompanyService;
import com.hlkj.baojin.service.DeviceService;
import com.hlkj.baojin.service.HKWebService;
import com.hlkj.baojin.soket.MyWebSocket;
import com.hlkj.baojin.utils.ErrororUtil;
import com.hlkj.baojin.utils.bean.JsonResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 徐其伟
 * @Description:
 * @date 19-1-2 下午4:28
 */
@RestController
@RequestMapping("/hkws")
public class WebServiceController {
    @Autowired
    private HKWebService hkWebService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private CompanyService companyService;

    @ApiOperation(value = "获取资源ZTree 1000组织机构 10000监控点 2000监控", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Organization.class)})
    @GetMapping(value = "/resource/ZTree/{resType}")
    public void getResource(@PathVariable String resType) {
        response.setContentType("text/xml;charset=UTF-8");
        try {
            response.getWriter().print(JSON.toJSON(hkWebService.getResource(resType)).toString().replaceAll("orgName", "name"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "根据监控系统公司id查询公司和摄像头ZTree", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Organization.class)})
    @GetMapping(value = "/org/{id}/camera/ZTree")
    public void getOrgAndCameraZTreeByOrg(@PathVariable String id) {
        response.setContentType("text/xml;charset=UTF-8");
        try {
            response.getWriter().print(JSON.toJSON(hkWebService.getOrgAndCameraZTreeByOrgId(id)).toString()
                    .replaceAll("orgName", "name")
                    .replaceAll("orgId", "parentId"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "socketClear", tags = {"socketClear"})
    @GetMapping(value = "/webSocket/clear")
    public void webSocketSetClear() {
        MyWebSocket.webSocketSet.clear();
    }
    @ApiOperation(value = "socketClear", tags = {"socketClear"})
    @GetMapping(value = "/webSocket/sendInfo/{userId}")
    public void sendInfo(@PathVariable String userId) {
        MyWebSocket.sendInfo("1111",userId);
    }


    @ApiOperation(value = "根据设备deviceId查询所关联的公司和其他摄像头ZTree", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Organization.class)})
    @PostMapping(value = "/cameras/org/ZTree/device/{deviceId}")
    public void getOrgAndCameraZTreeByDevice(@PathVariable String deviceId) {
        DeviceDto device = deviceService.findDeviceById(deviceId);
        ErrororUtil.isTrue(device == null || device.getMonitorDtoList() == null, "获取视频流", "设备未绑定监控");
        List<String> strings = device.getMonitorDtoList().stream().map(MonitorDto::getMonitorId).collect(Collectors.toList());
        String[] indexCodes = strings.toArray(new String[strings.size()]);
//        String[] indexCodes = {"001799","001592"};
        response.setContentType("text/xml;charset=UTF-8");
        try {
            response.getWriter().print(JSON.toJSON(hkWebService.getOrgAndCameraZTreeByCamera(indexCodes)).toString()
                    .replaceAll("orgName", "name")
                    .replaceAll("orgId", "parentId"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "根据设备indexCode数组查询所关联的公司和其他摄像头ZTree", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Organization.class)})
    @PostMapping(value = "/cameras/org/ZTree/indexCode/{indexCode}")
    public void getOrgAndCameraZTreeByIndexCode(@PathVariable String indexCode) {
        String[] indexCodes = {indexCode};
        response.setContentType("text/xml;charset=UTF-8");
        try {
            response.getWriter().print(JSON.toJSON(hkWebService.getOrgAndCameraZTreeByCamera(indexCodes)).toString()
                    .replaceAll("orgName", "name")
                    .replaceAll("orgId", "parentId"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "获取资源 1000组织机构 10000监控点 2000监控", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Organization.class)})
    @GetMapping(value = "/resource/{resType}")
    public ResponseEntity<JsonResult> alarmList(@PathVariable String resType) {
        return ResponseEntity.ok(JsonResult.success(hkWebService.getResource(resType)));
    }
    @ApiOperation(value = "获取组织机构树形图", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Organization.class)})
    @GetMapping(value = "/organization/tree")
    public ResponseEntity<JsonResult> getOrganizationTree() {
        return ResponseEntity.ok(JsonResult.success(hkWebService.getOrganizationTree()));
    }
    @ApiOperation(value = "获取监控系统token", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Organization.class)})
    @GetMapping(value = "/token")
    public ResponseEntity<JsonResult> getToken() {
        return ResponseEntity.ok(JsonResult.success(hkWebService.getToken()));
    }
    @ApiOperation(value = "获取监控节点", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = CameraInfo.class)})
    @GetMapping(value = "/camera/{indexCode}")
    public ResponseEntity<JsonResult> getCamera(@PathVariable String indexCode) {
        return ResponseEntity.ok(JsonResult.success(hkWebService.listCameraByOrgIndexCode(indexCode)));
    }
    @ApiOperation(value = "根据报警系统id查询该公司的所有摄像头", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = CameraInfo.class)})
    @GetMapping(value = "/company/{id}/camera/list")
    public ResponseEntity<JsonResult> cameraList(@PathVariable String id) {
        return ResponseEntity.ok(JsonResult.success(companyService.cameraList(id)));
    }
    @ApiOperation(value = "获取监控节点ZTree", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = CameraInfo.class)})
    @PostMapping(value = "/camera/ZTree")
    public void getCameraZTree(String indexCode) {
        response.setContentType("text/xml;charset=UTF-8");
        try {
            response.getWriter().print(JSON.toJSON(hkWebService.listCameraByOrgIndexCode(indexCode)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "获取绑定视频流xml", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = void.class)})
    @GetMapping(value = "/camera/stream/{indexCode}")
    public ResponseEntity<JsonResult> getStream(@PathVariable String indexCode) {
        List<String> strings = Lists.newArrayList(indexCode);
//        List<String> strings = Lists.newArrayList("001074", "001077", "001073" , "001075");
        Map<String,String> result = Maps.newHashMap();
        strings.forEach(s -> {
            List<CameraInfo> camera = hkWebService.getCameraByIndexCode(s);
            ErrororUtil.isTrue(camera.size() == 0, "获取视频流", "设备绑定监控编号错误");
            result.put("camera" + camera.get(0).getId(), hkWebService.getStream(s));
        });
        return ResponseEntity.ok(JsonResult.success(result));
    }
    @ApiOperation(value = "根据device获取多个视频流xml ", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = void.class)})
    @GetMapping(value = "/camera/stream/list/{deviceId}")
    public ResponseEntity<JsonResult> getStreamXmlList(@PathVariable String deviceId) {
        DeviceDto device = deviceService.findDeviceById(deviceId);
        ErrororUtil.isTrue(device == null || device.getMonitorDtoList() == null, "获取视频流", "设备未绑定监控");
        List<String> strings = device.getMonitorDtoList().stream().map(MonitorDto::getMonitorId).collect(Collectors.toList());
//      List<String> strings = Lists.newArrayList("001799","001592");
        Map<String,String> result = Maps.newHashMap();
        strings.forEach(s -> {
            List<CameraInfo> camera = hkWebService.getCameraByIndexCode(s);
            ErrororUtil.isTrue(camera.size() == 0, "获取视频流", "设备绑定监控编号错误");
            result.put("camera" + camera.get(0).getId(), hkWebService.getStream(s));
        });
        return ResponseEntity.ok(JsonResult.success(result));
    }
//2019-01-25T00:00:00Z
    @ApiOperation(value = "视频回放流xml", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = void.class)})
    @PostMapping(value = "/camera/playback/stream")
    public void getPlaybackInfo(String indexCode, String beginTime, String endTime, String storeType) {
        response.setContentType("text/xml;charset=UTF-8");
        try {
            response.getWriter().print(JSON.toJSON(hkWebService.getPlaybackInfo(indexCode, beginTime, endTime, storeType)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @ApiOperation(value = "根据device获取多个回放视频流xml ", tags = {"视频模块"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = void.class)})
    @PostMapping(value = "/camera/playback/stream/list/{deviceId}")
    public ResponseEntity<JsonResult>  getPlaybackStreamXmlList(@PathVariable String deviceId, Long beginTime, Long endTime, String storeType) {
        DeviceDto device = deviceService.findDeviceById(deviceId);
        ErrororUtil.isTrue(device == null || device.getMonitorDtoList() == null, "获取视频流", "设备未绑定监控");
        List<String> strings = device.getMonitorDtoList().stream().map(MonitorDto::getMonitorId).collect(Collectors.toList());
//      List<String> strings = Lists.newArrayList("001799","001592");
        Map<String,String> result = Maps.newHashMap();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
//        sdf.setTimeZone(UTC);
//        System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
//        DateTimeFormatter simpleDateFormat = new DateTimeFormatter("");
        String begin = simpleDateFormat.format(new Date(beginTime));
        String end = simpleDateFormat.format(new Date(endTime));

        strings.forEach(s -> {
            List<CameraInfo> camera = hkWebService.getCameraByIndexCode(s);
            ErrororUtil.isTrue(camera.size() == 0, "获取视频流", "设备绑定监控编号错误");
            result.put("camera" + camera.get(0).getId(), hkWebService.getPlaybackInfo(s, begin, end, storeType));
        });
        return ResponseEntity.ok(JsonResult.success(result));
    }
}
